<template>
	<div class="newShop">
		<div class="newShop_top">
			<div class="into_index">首页<i class="el-icon-close"></i></div>
			<div class="current">{{text}}<i class="el-icon-close"></i></div>
		</div>
		<div class="newShop_title">
			<div class="newShop_title_left">在售商品/<i>{{text}}</i></div>
			<div class="newShop_title_right">
				<button class="newShop_title_right_btn" v-if="id != 1" @click="handerBase">返回</button>
			</div>
		</div>
		<div class="newShop_tabs">
			<div class="newShop_tabs_title">
				<div @click="handerTabs(i)" class="newShop_tabs_title_information"
					:class="[tabsIndex == i ? 'tabs_active' : '']" v-for="(v,i) in tabs" :key="i">{{v}}</div>
			</div>
			<!-- 基本信息 -->
			<div class="newShop_tabs_content_box" v-if="information">
				<div class="newShop_tabs_content_boxs">
					<!-- 基本信息 -->
					<div class="newShop_tabs_content">
						<div class="newShop_tabs_content_left">基本信息</div>
						<div class="newShop_tabs_content_right">
							<form>
								<!-- 商品名称 -->
								<div class="shopName">
									<div class="shopName_name" :class="{'rules' : nameColor}">商品名称</div>
									<div class="shopName_input">
										<input :class="{'rules_input' : nameNull}" type="text" v-model="form.name"
											@blur="handerName">
										<div class="shopName_input_title">
											<font v-if="nameNull">商品名称不能为空</font>
											<font v-if="unitNull">商品单位不能为空</font>
										</div>
									</div>
									<div class="shopName_unit">
										<input :class="{'rules_input' : unitNull}" type="text" placeholder="单位,如个/件/包"
											v-model="form.unit" @blur="handerUnit">
									</div>
								</div>
								<!-- 关键字 -->
								<div class="keyword">
									<div class="keyword_left">关键字</div>
									<div class="keyword_right">
										<input type="text" v-model="form.keywords">
										<div class="keyword_right_title">
											商品关键字，能准确搜到商品的，比如：海尔电视|电视 之类的
										</div>
									</div>
								</div>
								<!-- 商品类型 -->
								<!-- <div class="shoptype">
									<div class="shoptype_left">商品类型</div>
									<div class="shoptype_right">
										<div class="shoptype_right_radio">
											<el-radio :disabled="disabled" v-model="form.shoptype" label="1">实体商品</el-radio>
											<el-radio :disabled="disabled" v-model="form.shoptype" label="2">虚拟商品</el-radio>
											<el-radio :disabled="disabled" v-model="form.shoptype" label="3">卡密</el-radio>
											<el-radio :disabled="disabled" v-model="form.shoptype" label="4">批发商品</el-radio>
											<el-radio :disabled="disabled" v-model="form.shoptype" label="5">计次/计时商品</el-radio>
										</div>
										<div class="shoptype_right_title">
											商品类型，商品保存后无法修改，请谨慎选择
										</div>
									</div>
								</div> -->
								<!-- 商家售卖类型 -->
								<div class="classif" v-if="sale_type == 1">
									<div class="classif_left shopName_name">售卖类型</div>
									<div class="classif_right" style="display: flex;align-items: center">
										<el-radio v-model="form.sale_type" label="1" @change="handleSaleType">家居
										</el-radio>
										<el-radio v-model="form.sale_type" label="2" @change="handleSaleType">泛家居
										</el-radio>
									</div>
								</div>
								<!-- 商品分类 -->
								<div class="classif">
									<div class="classif_left ">商品分类</div>
									<div class="classif_right">
										<el-cascader @change="handerClassif" :options="cateList" :props="cate"
											v-model="form.classification" :show-all-levels="false"
											placeholder="请选择商品分类"></el-cascader>
									</div>
								</div>
								<!-- 酷品秀 -->
								<div class="shopimg">
									<div class="shoptype_left">酷品秀</div>
									<div class="shopimg_right">
										<input class="shopimg_right_title" v-model="form.kpx" placeholder="酷品秀模型ID"
											@blur="changekpx" />
									</div>
								</div>
								<div class="shopImg" id="kpx-box" style="display: none;">
									<div id="kpx" style="display: block;width: 200px;height: 200px;"></div>
								</div>
								<!-- 商品图片 -->
								<!-- <div class="shopimg">
									<div class="shopimg_left">商品图片</div>
									<div class="shopimg_right">
										<input class="shopimg_right_title" readonly :class="[form.img.length == 0 ? 'input_No' : '' ]" v-model="form.img" placeholder="批量上传图片"/>
										<input class="shopimg_right_file" type="file" accept="image/png, image/jpeg, image/gif, image/jpg" title="" @change="handerFile">
										<div class="shopimg_right_btn">选择图片</div>
									</div>
								</div>
								<div class="shopImg" v-loading="loading" element-loading-text="图片上传中" element-loading-background="rgba(0, 0, 0, 0.5)">
                  <div class="shopImgBox" v-for="(item,index) in imagesUrl" :key="index">
									    <img :src="item.image_path" alt="">
                      <div class="shopImgDelete"><i class="el-icon-delete" @click="deleteImg(index)"></i></div>
                  </div>
                  <div style="clear:both;"></div>
                </div> -->
								<div class="shopimg">
									<div class="shopimg_left">商品图片</div>
									<div class="shopimg_right">
										<el-upload action="/api/client/base/uploadfile" list-type="picture-card"
											:on-preview="handlePictureCardPreview" ref="upload"
											:on-remove="handleRemove" :on-success="handleAvatarSuccess"
											:before-upload="beforeAvatarUpload" :auto-upload="true" :limit="50"
											:headers="myHeaders" :file-list="fileList"
											accept="image/jpeg, image/jpg, image/gif, image/png" multiple>
											<i class="el-icon-plus"></i>
										</el-upload>
										<el-dialog :visible.sync="dialogVisible">
											<img width="100%" :src="dialogImageUrl" alt="">
										</el-dialog>
									</div>
								</div>
								<p style="color:#a0a0a0;padding:10px 0 0 100px;">（每张图片大小不超过2M，尺寸建议宽度为640，并保持图片大小一致）</p>

								<!-- 商品属性 -->
								<div class="shoptypes">
									<div class="shoptypes_left">商品属性</div>
									<div class="shoptypes_right">
										<el-checkbox-group v-model="form.shoptypes">
											<el-checkbox label="1">推荐</el-checkbox>
											<el-checkbox label="2">新品</el-checkbox>
											<el-checkbox label="3">热卖</el-checkbox>
											<el-checkbox label="4">包邮</el-checkbox>
											<el-checkbox label="5">不参与会员折扣</el-checkbox>
											<el-checkbox label="6">特价商品</el-checkbox>
										</el-checkbox-group>
									</div>
								</div>
							</form>
						</div>
					</div>
					<!-- 商品信息 -->
					<div class="newShop_tabs_shopinfo">
						<div class="newShop_tabs_shopinfo_left">商品信息</div>
						<div class="newShop_tabs_shopinfo_right">
							<form>
								<!-- 商品价格 -->
								<div class="shopprice">
									<div class="shopprice_left">商品价格</div>
									<div class="shopprice_right">
										<div class="shopprice_right_box">
											<div class="shopprice_right_box_title">售价</div><input type="number"
												@blur="inputPrice" v-model="form.price" />
											<div class="shopprice_right_box_title">元 原价</div><input type="number"
												@blur="inputPriced" v-model="form.priced" />
											<div class="shopprice_right_box_title">元</div>
											<!-- <input type="number" @blur="inputCostPrice" v-model="form.cost" />
											<div class="shopprice_right_box_title">元</div> -->
										</div>
										<div class="shopprice_right_box">
											<!-- <div class="shopprice_right_box_title">比率</div>
											<input type="number" v-model="form.rate" @blur="toFloorPrice" /> -->
											<div class="shopprice_right_box_title">分佣比率</div>
											<input type="number" v-model="form.promotor_rate" @blur="inputRate" />

											<!--  <div class="shopprice_right_box_title">底价</div><input type="number" readonly v-model="floorPrice" /> -->
											<div class="shopprice_right_box_title">(%)</div>
										</div>
										<div class="shopprice_right_title">
											尽量填写完整，有助于商品销售的数据分析
										</div>
										<div class="shopprice_right_payment">
											<el-checkbox-group v-model="form.payment">
												<el-checkbox label="1">支持货到付款</el-checkbox>
												<el-checkbox label="2">支持收银台</el-checkbox>
												<el-checkbox label="3">支持发票</el-checkbox>
											</el-checkbox-group>
										</div>
									</div>
								</div>
								<!-- 运费设置 -->
								<!-- <div class="freight">
									<div class="freight_left">运费设置</div>
									<div class="freight_right">
										<div class="freight_right_top">
											<el-radio v-model="form.freight" label="1">运费模板</el-radio>
											<el-select v-model="form.template" placeholder="选择模板">
											    <el-option
												 v-for="v in freightAll"
												 :key="v.move_id"
												 :label="v.freight_name"
												 :value="v.move_id"></el-option>
											  </el-select>
										</div>
										<div class="freight_right_bottom">
											<el-radio v-model="form.freight" label="2">统一邮费</el-radio>
											<div class="freight_right_bottom_price">
												<input type="text" v-model="form.freightPrice">
												<div class="freight_right_bottom_price_text">元</div>
											</div>
										</div>
									</div>
								</div> -->
								<div class="shelves">
									<div class="shelves_left">加入选材中心</div>
									<div :class="[form.setMaterial==1?'shelves_right shelves_space':'shelves_right']">
										<el-radio v-model="form.setMaterial" label="0">否</el-radio>
										<el-radio v-model="form.setMaterial" label="1">是</el-radio>
										<div class="shopprice_right" style="margin-top:10px;"
											v-if="form.setMaterial==1">
											<div class="shopprice_right_box">
												<div class="shopprice_right_box_title">供货价</div>
												<input type="number" v-model="form.cost" @blur="inputCostPrice" />
												<div class="shopprice_right_box_title">元</div>
											</div>
											<div class="cost_price_title" style="color: #8b8b8b;">
												供货价是提供装企（设计师, 施工队）进行采购的结算价！
											</div>
										</div>
									</div>
								</div>
								<!-- <div class="shopprice" style="margin: 10px 0% 0px 0%;">
									<div class="shelves_left"></div>
									<div class="shopprice_right">
										<div class="shopprice_right_box">
											<div class="shopprice_right_box_title">供货价</div>
											<input type="number" v-model="form.cost" @blur="inputCostPrice" />
											<div class="shopprice_right_box_title">元</div>
										</div>
									
									</div>
								</div> -->
								<!-- 上架 -->
								<div class="shelves">
									<div class="shelves_left">上架</div>
									<div class="shelves_right">
										<el-radio v-model="form.shelves" label="0">否</el-radio>
										<el-radio v-model="form.shelves" label="1">上架</el-radio>
									</div>
								</div>
								<!-- 是否定金付款 -->
								<div class="shelves">
									<div class="shelves_left">定金付款</div>
									<div class="shelves_right">
										<el-radio v-model="form.set_deposit_status" label="0">否</el-radio>
										<el-radio v-model="form.set_deposit_status" label="1">是</el-radio>
									</div>
								</div>
								<div class="seckill_date_range" v-if="form.set_deposit_status == '1'">
									<div class="left" style="line-height:40px;">定金比率</div>
									<div class="right" style="display: flex;">
										<input type="number" v-model="form.deposit_rate" @blur="setDeposit">
									</div>
									<div>% <span style="color:#bbb;">（1-100之间）</span></div>
								</div>
								<div class="shelves">
									<div class="shelves_left">消费限制</div>
									<div class="shelves_right">
										<el-radio v-model="form.purchase_limit" :label="0">不限制</el-radio>
										<el-radio v-model="form.purchase_limit" :label="1">限制</el-radio>
									</div>
								</div>
								<div class="shelves" v-if="form.purchase_limit==1">
									<div class="shelves_left">限制金额</div>
									<div class="shelves_right">
										<input type="number" v-model="form.limit_amount" @blur="toFloorPrice" />
									</div>
								</div>
								<!-- 上架时间 -->
								<!-- <div class="shelvesTime">
									<div class="shelvesTime_left">是否选择上架时间</div>
									<div class="shelvesTime_right">
										<el-radio v-model="form.shelvesTime" label="0">否</el-radio>
										<el-radio v-model="form.shelvesTime" label="1">是</el-radio>
										<el-date-picker
										      v-model="form.shelves_time"
										      type="datetimerange"
											    :disabled="form.shelvesTime=='0'?true:false"
										      range-separator="至"
										      start-placeholder="开始日期"
										      end-placeholder="结束日期">
										    </el-date-picker>
										<div class="shelvesTime_right_title">
											商品在选择时间内自动上架，过期自动下架
										</div>
									</div>
								</div> -->
							</form>
						</div>
					</div>
				</div>
				<div class="newShop_tabs_content_btn">
					<button class="save" @click="save(1)">下一步</button>
				</div>
			</div>
			<!-- 规格/库存 -->
			<div class="newShop_specifications" v-if="specifications">
				<div class="newShop_specifications_box">
					<div class="newShop_specifications_box_left">规格/库存</div>
					<div class="newShop_specifications_box_right">
						<form>
							<div class="coding">
								<div class="coding_left">编码</div>
								<div class="coding_right">
									<div class="codings">编码</div><input class="coding_ipt"
										:class="{'ipt_actives' : !hiddYesNo}" type="number" v-model="form.codings" />
									<div class="codings">条码</div><input class="coding_ipt"
										:class="{'ipt_actives' : !hiddYesNo}" type="number" v-model="form.codingss" />
									<div class="codings">重量</div><input class="coding_ipt"
										:class="{'ipt_actives' : !hiddYesNo}" type="number" v-model="form.codingsss" />
									<div class="codings">克</div>
								</div>
							</div>
							<div class="inventory">
								<div class="inventory_box">
									<div class="inventory_box_left">库存</div>
									<div class="inventory_box_right">
										<input type="number" v-model="form.inventory"
											:class="{'ipt_actives' : !hiddYesNo}" />
										<div class="inventory_box_right_box">
											<div :class="{'hidd_active' : hiddIpt}" @click="handerIpt" class="hidd_ipt">
												<i class="el-icon-check"></i></div>显示库存
										</div>
										<el-radio v-model="form.reduInventory" label="1">拍下减库存</el-radio>
										<el-radio v-model="form.reduInventory" label="2">付款减库存</el-radio>
										<el-radio v-model="form.reduInventory" label="3">永不减库存</el-radio>
									</div>
								</div>
								<div class="inventory_title">
									<div class="inventory_title_left"></div>
									<div class="inventory_title_right">商品的属于数量，如启用多规格或为虚拟卡密产品，则此处设置无效</div>
								</div>
							</div>
							<div class="yesNo">
								<div class="yesNo_box">
									<div class="yesNo_box_left"></div>
									<div class="yesNo_box_right">
										<div class="yesNo_box_right_box" :class="{'yesNo_active' : hiddYesNo}"
											@click="handerYesNo">
											<i class="el-icon-check"></i>
										</div>
										启用商品规格
									</div>
								</div>
								<div class="yesNo_title">
									<div class="yesNo_title_left"></div>
									<div class="yesNo_title_right">
										启用商品规格后，商品的规格及库存以商品规格为准。库存设置为0则会到“已售罄”，手机也不会显示，-1为不限制
									</div>
								</div>
							</div>

							<div class="specTitle" v-if="!hiddYesNo">
								1.拖动规格克调整规格显示顺序，更改规格及规格项后请点击下方的【刷新规格项目表】来更新数据。<br />
								2.每一种规格代表不同型号，例如颜色为一种规格，尺寸为一种规格，如果设置多规格，手机用户必须每一种规格都选择一个规格项，才能添加购物车或购买。
							</div>
							<!--  v-for="(v,i) in form.specifAll" :key="i" -->
							<div class="addSpacItem" v-if="!hiddYesNo">
								<div class="addSpacItem_top">
									<div class="addSpacItem_top_box">
										<input type="text" v-model="title" maxlength="6">
										<div class="addItems" @click="addSpecif"><i class="el-icon-plus"></i>添加规格</div>
									</div>
									<div class="addSpacItem_top_text" v-if="hiddspecifs">
										规格名称不能为空
									</div>
								</div>
								<div class="addSpacItem_bottom">
									<ul>
										<!-- v-for="(item,index) in v.child" :key="index"
                    	v-dragging="{ list: v.child, item: item, group: 'index' }" -->
										<li v-for="(item,index) in list" :key="index">
											<div class="sku_title">
												<h5>{{item.title}}</h5>
												<div class="li_down" @click="downSpecif(index)"><i
														class="el-icon-close"></i></div>
												<!-- <div class="spec_file">
                          <i class="el-icon-upload2" v-if="!item.img"></i>
                          <input type="file" v-if="!item.img" @change="handerFiles($event,index)"/>
                          <img :src="item.img" alt="">
                        </div> -->
												<input type="text" v-model="item.value" maxlength="6"
													placeholder="请输入规格值" password />

												<div class="addBtn" @click="addSku_child(index)">添加</div>
											</div>

											<!-- 循环规格属性值 -->
											<div class="sku_child" style="display:flex;"
												v-for="(item1,index1) in item.list" :key="index1">
												<div class="li_select">
													<img :src="item1.img" alt="" />
												</div>
												<span>{{item1.value}}</span>
												<div class="li_down" @click="downSpecif_child(index,index1)"><i
														class="el-icon-close"></i></div>
												<div class="li_rank"><i class="el-icon-rank"></i></div>
											</div>
										</li>
									</ul>
								</div>
							</div>

							<div class="refresh" v-if="!hiddYesNo">
								<div class="refresh_btn">
									<!-- <button @click="addSpecifs"><i class="el-icon-plus"></i>添加规格</button> -->
									<button type="button" @click="refreshSku"><i
											class="el-icon-refresh-left"></i>刷新规格项目表</button>
								</div>
								<div class="refresh_title" v-if="hiddtitle">
									规格发生变化，请刷新规格项目表
								</div>
							</div>

							<div v-if="hiddsku">
								<div class="detailed">
									<!-- 规格表内容 -->
									<table>
										<thead>
											<tr>
												<th style="text-align:center;" v-for="(item, index) in tableTitle"
													:key="index">{{item}}</th>
												<!-- <th style="text-align:center;" v-if="tableTitle.length">底价</th> -->
											</tr>
										</thead>
										<tbody>
											<tr v-for="(item,index) in tableContent" :key="index">
												<td v-for="(item2,index2) in item" :class="item2.type=='规格'?'type':''"
													:key="index2">
													<div v-if="item2.type=='规格'">{{item2.value}}</div>
													<div v-if="item2.type=='规格图'" class="spec_file">
														<i class="el-icon-upload2" v-if="!item2.path"></i>
														<input type="file" v-if="!item2.path"
															@change="handerFiles($event,index,index2)" />
														<img :src="item2.path" alt="">
													</div>
													<input v-if="item2.type=='库存'" type="number" v-model="item2.value"
														style="width:100px" />
													<input v-if="item2.type=='原价'" type="number" v-model="item2.value"
														@blur="price1(index,item2.value,index2)" style="width:100px" />
													<input v-if="item2.type=='售价'" type="number" v-model="item2.value"
														@blur="price2(index,item2.value,index2)" style="width:100px" />
													<input v-if="item2.type=='供货价'" :disabled="setMaterialFn"
														type="number" @blur="price3(index,item2.value,index2)"
														v-model="item2.value" style="width:100px" />
												</td>
												<!-- 计算每个规格底价 -->
												<!-- <td>
                            <input readonly style="width:100px" type="number" :value="calcula(item)">
                          </td> -->
											</tr>
										</tbody>
									</table>
								</div>
							</div>
						</form>
					</div>
				</div>
				<div class="newShop_specifications_btn">
					<button class="bast" @click="save(0)">上一步</button>
					<button class="save" @click="save(2)">下一步</button>
				</div>
			</div>
			<!-- 商品详情 -->
			<div class="newShop_details" v-if="details">
				<div class="newShop_details_box">
					<div class="newShop_details_box_left">内容</div>
					<div class="newShop_details_box_right">
						<form>
							<div class="subtitle">
								<div class="subtitle_left">商品副标题</div>
								<div class="subtitle_right">
									<input type="text" v-model="form.subtitle">
								</div>
							</div>
							<div class="shorttitle">
								<div class="shorttitle_left">商品短标题</div>
								<div class="shorttitle_right">
									<input type="text" v-model="form.shorttitle">
								</div>
							</div>
							<div class="shorttitle">
								<div class="shorttitle_left">商品详情</div>
								<div class="shorttitle_right">
									<!-- <VueEditor :config="config" ref='myeditor'/> -->
									<div style="width:600px;height:600px;">
										<!--上传图片时得加载画面-->
										<VueEditor style="width: 100%;" v-loading="editorLoading"
											element-loading-text="图片上传中" element-loading-background="rgba(0, 0, 0, 0.5)"
											useCustomImageHandler @image-added="handleImageAdded"
											:editorToolbar="customToolbar" v-model="form.details"></VueEditor>
									</div>
								</div>
							</div>
						</form>
					</div>
				</div>
				<div class="newShop_details_btn">
					<button class="bast" @click="save(1)">上一步</button>
					<button class="save" @click="saveFile">保存信息</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	// import VueEditor from "vue-word-editor";
	// import "quill/dist/quill.snow.css";
	import upload from "@/apis/mall";
	import {
		setTimeout
	} from "timers";
	import {
		VueEditor
	} from "vue2-editor";
	import {
		log
	} from "util";
	import {
		isIP
	} from "net";
	import E from 'wangeditor';
	import kujiale from '../kujiale/sdk.min.js';
	export default {
		data() {
			return {
				disabled: false, //编辑时返回的id
				title: "", //规格名称
				list: [], //表中生成前的数据
				tableTitle: [], //表头
				tableContent: [], //生成后表中的数据
				tabNew: false,
				id: "",
				text: "新增商品",
				information: true,
				specifications: false,
				details: false,
				tabs: ["编辑基本信息", "规格/库存", "编辑商品详情"],
				tabsIndex: 0,
				detailedTitle: [
					"",
					"库存",
					"现价",
					"原价",
					"供货价",
					"编码",
					"条码",
					"重量（克）"
				],
				nameColor: false, // 用户没有输入时
				nameNull: false, // 商品名称为空
				unitNull: false, // 商品单位为空
				hiddIpt: false, // 是否显示库存
				hiddspecifs: false, // 规格项为空时
				hiddsku: false, // 规格项为空时规格列表不显示
				hiddtitle: false, // 刷新规格表提示文字
				hiddYesNo: true, // 是否启用商品规格
				imagesUrl: [], //商品图片
				img: [], // 规格图片
				fileList: [],
				dialogImageUrl: "",
				dialogVisible: false,
				myHeaders: {
					'access-token': this.$store.state.token, //这里重新定义了请求头
					'Authorization': this.$store.state.token,
					'user-id': this.$store.state.user_id
				},
				dialogImageUrl: '',
				dialogVisible: false,
				customToolbar: [
					[{
						'header': [false, 1, 2, 3, 4, 5, 6]
					}], //标题
					['bold', 'italic', 'underline'], //加粗\斜体\下划线
					['italic'], //斜体----也可以拆开来写，用于换位置顺序
					[{
						'align': ''
					}, {
						'align': 'center'
					}, {
						'align': 'right'
					}], //对齐
					[{
						'list': 'ordered'
					}, {
						'list': 'bullet'
					}, {
						'list': 'check'
					}], //有序无序列表
					[{
						'background': []
					}, {
						'color': []
					}], //背景色
					['image', 'link'], //图片、链接
					['strike'], //作废（文字中间一横）
					['underline'],
					['clean'], //清楚格式（所谓去掉背景色这些花里胡巧）
					['code'], //代码
					['code-block'], //代码块
					// ['video'] //视频
				],

				// 分类列表
				cateList: [],
				cate: {
					value: "cate_id",
					label: "cate_name",
					children: "child",
					expandTrigger: "hover"
				},
				// 运费模板
				freightAll: [],
				trNum: 1,
				sku_value: [], //属性值组
				form: {
					name: "", // 商品名字
					unit: "件", // 单位
					keywords: "", // 关键字
					shoptype: "1", // 商品类型
					classification: "", // 商品分类
					img: [], // 商品图片(轮播图)
					shoptypes: [], // 商品属性
					price: "", // 售价
					priced: "", // 原价
					cost: "", // 供货价
					payment: [], // 付款方式
					freight: "1", // 运费设置
					template: "", // 运费模板
					freightPrice: "", // 邮费
					shelves: "1", // 上架
					shelvesTime: "0", // 上架时间
					shelves_time: [], // 选择时间
					subtitle: "", // 商品副标题
					shorttitle: "", // 商品短标题
					codings: "", // 编码
					codingss: "", // 条码
					codingsss: "", // 重量
					inventory: "", // 库存
					details: "",
					according: "1", // 是否显示库存
					reduInventory: "1", // 减库存
					specsType: "1", // 单多规格
					specifAll: [], // 规格项列表
					sku: [], // 规格列表
					kpx: '',
					spec_sku: [],
					spec_typelist: [], // 规格属性列表
					rate: 0, //比率
					set_deposit_status: '0', //是否定金付款
					deposit_rate: 10, //定金比率
					sale_type: '1',
					setMaterial: '0', //加入选材中心
					purchase_limit: '', //消费限制
					limit_amount: '', //限制金额
          promotor_rate:0, //分佣比率
				},
				floorPrice: null, //底价
				store_id: null,

				editor: null,
				editorData: '',
				loading: false, //商品图片loading
				editorLoading: false, //富文本图片loading
				sale_type: 1, //1 家居 2 泛家居

				market_id: '', //卖场id
			};
		},

		mounted() {
			this.sale_type = this.$route.query.sale_type;
			if (this.sale_type == 2) {
				this.form.sale_type = '2'
			}
			console.log(this.sale_type, 'saletype', this.form.sale_type);

			let id = this.$route.query.id;
			this.store_id = this.$route.query.store_id;
			this.market_id = this.$route.query.market_id; //卖场id
			this.Id();
			// 拖动排序
			this.$dragging.$on("dragged", value => {});
			this.init();
			// console.log(this.$route.query.store_id);

			if (id) {
				this.disabled = true;
			} else {
				this.disabled = false;
			}
		},
		computed: {
			setMaterialFn() {
				if (this.form.setMaterial == 0) {
					return true
				} else {
					return false
				}
			}
		},
		methods: {
			//选择售卖类型
			handleSaleType(val) {
				console.log(val, '1');
				// this.form.sale_type = val;
				this.init();
			},
			handleRemove(file, fileList) {
				this.fileList = fileList
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			handleAvatarSuccess(res, file, fileList) {
				this.fileList = fileList
			},
			beforeAvatarUpload(file) {
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isLt2M) {
					this.$message.error('上传商品图片大小不能超过 2MB!');
				}
				return isLt2M;
			},
			// 获取页面id
			Id() {
				// console.log(this.$route.query);
				let id = this.$route.query.id;
				if (id) {
					this.text = '编辑商品'
					this.$http
						.post("/api/root/ProductShop/detail", {
							product_id: id
						})
						.then(res => {
							// console.log(res);
							if (res.code == 1) {
								let data = res.data;
								// console.log(data);
								this.form.id = data.id;
								this.form.name = data.product_title;
								this.form.unit = data.unit;
								this.form.keywords = data.keyword;
								this.form.classification = data.cate_id;
								// console.log(data.round_imgs);
								let imgId = data.round_imgs.map(item => item.image_id);
								imgId.map(item => {
									this.form.img.push(item);
								});
								// console.log(imgId);
								// this.form.img.concat(imgId)
								//  console.log(this.form.img);
								this.imagesUrl = data.round_imgs;
								data.round_imgs.map(item => {
									this.fileList.push({
										id: item.image_id,
										url: item.image_path
									})
								});
								// this.imagesUrl.push(data.round_imgs.map(item=>item.image_path))
								// console.log(this.imagesUrl);
								this.form.shoptype = data.product_type.toString();
								this.form.shoptypes = data.s_type.split(",");
								this.form.price = data.price;
								this.form.priced = data.primary_price;
								this.form.cost = data.cost_price;
								this.form.payment = data.pay_way.split(",");
								this.form.freight = data.move_type.toString();
								this.form.template = data.move_id;
								this.form.freightPrice = data.move_price;
								this.form.codings = data.code;
								this.form.codingss = data.barcode;
								this.form.codingsss = data.weight;
								this.form.inventory = data.num;
								this.form.kpx = data.cool_show;
								this.form.shelves = data.status.toString();
								this.form.shelvesTime = data.set_sale_time.toString();
								this.form.set_deposit_status = data.set_deposit_status == 1 ? '1' : '0'
								this.form.setMaterial = data.set_material == 1 ? '1' : '0' //选材中心
								this.form.deposit_rate = (data.deposit_rate * 100).toFixed(0)
                this.form.promotor_rate = data.promotor_rate
								// console.log(data.start_sale_time,data.end_sale_time);
								this.form.shelves_time = [
									this.$moment(data.start_sale_time * 1000).format("YYYY-MM-DD"),
									this.$moment(data.end_sale_time * 1000).format("YYYY-MM-DD")
								];
								// console.log(this.form.shelves_time);
								// console.log(this.form.shelves_time);
								this.form.subtitle = data.subtitle;
								this.form.shorttitle = data.short_title;
								this.form.according = data.is_show_stock;
								this.form.details = data.details;
								this.form.purchase_limit = data.purchase_limit;
								this.form.limit_amount = data.limit_amount;
								this.form.rate = (data.rate * 100).toFixed(0); ////////////比率(百分比)
								this.floorPrice =
									data.rate * data.cost_price + Number(data.cost_price); ///////底价
								this.floorPrice.toFixed(2);

								if (this.form.according == 1) {
									this.hiddIpt = false;
									this.hiddsku = true;
								} else if (this.form.according == 2) {
									this.hiddIpt = true;
								}
								this.form.reduInventory = data.stock_type.toString();

								this.form.specsType = data.specs_type;
								if (this.form.specsType == 1) {
									this.hiddYesNo = true;
								} else if (this.form.specsType == 2) {
									this.hiddYesNo = false;
								}

								//将获取到的parameter值赋值给list
								if (data.parameter) {
									data.parameter.map((item, index) => {
										let arr = [];
										item.child.map(item => {
											// console.log(item);
											let obj = {
												value: item.specif ? item.specif : "",
												img: item.specimg
											};
											arr.push(obj);
										});
										let obj_list = {
											title: item.specifs ? item.specifs : "",
											sort: index,
											list: arr,
											new: false
										};
										this.list.push(obj_list);
									});
									// console.log(this.list);
									// console.log(data.parameter);

									//将获取到的sku_list赋值给tableContent

									// console.log(data.sku_lst);
									for (let i = 0; i < data.sku_lst.length; i++) {
										let skuObj = {};
										let sku_arr = [];
										//循环生成里面的obj
										for (let p = 0; p < data.sku_lst[0].attribute.length + 5; p++) {
											let skuObj = {
												value: "",
												type: "",
											};
											if (p == data.sku_lst[0].attribute.length + 4) {
												skuObj.type = "供货价";
											} else if (p == data.sku_lst[0].attribute.length + 3) {
												skuObj.type = "售价";
											} else if (p == data.sku_lst[0].attribute.length + 2) {
												skuObj.type = "原价";
											} else if (p == data.sku_lst[0].attribute.length + 1) {
												skuObj.type = "库存";
											} else if (p == data.sku_lst[0].attribute.length) {
												skuObj.type = "规格图";
											} else {
												skuObj.type = "规格";
												skuObj.key = "";
												skuObj.sku_id = data.sku_lst[i].id
											}
											sku_arr.push(skuObj);
										}
										// console.log(sku_arr);

										// console.log(data.sku_lst[i].attribute,'++++');
										for (let k = 0; k < data.sku_lst[i].attribute.length; k++) {
											for (const key in data.sku_lst[i].attribute[k]) {
												// console.log(key);
												sku_arr[k].key = data.sku_lst[i].attribute[k].key;
												sku_arr[k].value = data.sku_lst[i].attribute[k].value;
											}
										}
										sku_arr[sku_arr.length - 1].value =
											data.sku_lst[i].cost_price;
										sku_arr[sku_arr.length - 2].value = data.sku_lst[i].price;
										sku_arr[sku_arr.length - 3].value =
											data.sku_lst[i].primary_price;
										sku_arr[sku_arr.length - 4].value = data.sku_lst[i].num;
										sku_arr[sku_arr.length - 5].path = data.sku_lst[i].img;
										sku_arr[sku_arr.length - 5].img_id = data.sku_lst[i].img_id;
										this.tableContent.push(sku_arr); //然后把每一株数据push到tableContent
									}
									// console.log(this.tableContent);
									// 每个规格计算底价

									//获取tabletitle
									for (let n = 0; n < this.tableContent[0].length - 5; n++) {
										this.tableTitle.push(this.tableContent[0][n].key);
									}
									this.tableTitle.push("规格图", "库存", "原价", "售价", "供货价");
									// console.log(this.tableTitle);
									//展示酷品秀
								}
							}
							this.changekpx();
						});
				}
			},

			//多规格输入原价
			price1(index, value, index1) {
				console.log(index, value, index1, '11111')
				console.log(this.tableContent, '----');
				let nowData = this.tableContent[index]; //当前这一行
				let price2 = nowData[index1 + 1].value; //售价
				let price3 = nowData[index1 + 2].value; //供货价
				if ((value * 1) < (price2 * 1)) {
					this.$message.warning('原价不可小于售价')
					this.tableContent[index][index1].value = ''
				} else if ((value * 1) <= (price3 * 1)) {
					// this.$message.warning('原价不可小于供货价')
					// this.tableContent[index][index1].value = ''
				}
			},
			// 多规格输入售价
			price2(index, value, index1) {
				console.log(index, value, index1, '22222')
				console.log(this.tableContent, '----');
				let nowData = this.tableContent[index]; //当前这一行
				let price1 = nowData[index1 - 1].value; //原价
				let price3 = nowData[index1 + 1].value; //供货价
				if ((value * 1) <= (price3 * 1)) {
					// this.$message.warning('售价不可小于供货价')
					// this.tableContent[index][index1].value = ''
				} else if ((price1 * 1) && (value * 1) > (price1 * 1)) {
					this.$message.warning('售价不可大于原价')
					this.tableContent[index][index1].value = ''
				}
			},
			// 多规格输入供货价
			price3(index, value, index1) {
				console.log(index, value, index1, '33333')
				console.log(this.tableContent, '----');
				let nowData = this.tableContent[index]; //当前这一行
				let price1 = nowData[index1 - 2].value; //原价
				let price2 = nowData[index1 - 1].value; //售价
				if ((price2 * 1) && (value * 1) >= (price2 * 1)) {
					this.$message.warning('供货价不可大于售价')
					this.tableContent[index][index1].value = ''
				} else if ((price1 * 1) && (value * 1) >= (price1 * 1)) {
					this.$message.warning('供货价不可大于原价')
					this.tableContent[index][index1].value = ''
				}
			},




			// 输入原价
			inputPriced() {
				if ((this.form.priced * 1) < (this.form.price * 1)) {
					this.$message.warning('原价不可小于售价')
					this.form.priced = ''
				} else if ((this.form.priced * 1) <= (this.form.cost * 1)) {
					// this.$message.warning('原价不可小于供货价')
					// this.form.priced = ''
				}
			},
			// 输入售价
			inputPrice() {
				if ((this.form.price * 1) <= (this.form.cost * 1)) {
					// this.$message.warning('售价不可小于供货价')
					// this.form.price = ''
				} else if ((this.form.priced * 1) && (this.form.price * 1) > (this.form.priced * 1)) {
					this.$message.warning('售价不可大于原价')
					this.form.price = ''
				}
			},
			// 输入供货价
			inputCostPrice() {
				if ((this.form.price * 1) && (this.form.cost * 1) >= (this.form.price * 1)) {
					this.$message.warning('供货价不可大于售价')
					this.form.cost = ''
				} else if ((this.form.priced * 1) && (this.form.cost * 1) >= (this.form.priced * 1)) {
					this.$message.warning('供货价不可大于原价')
					this.form.cost = ''
				}
			},

			// 定金比率
			setDeposit() {
				let fag = /^([1-9][0-9]{0,1}|100)$/;
				if (!fag.test(this.form.deposit_rate)) {
					this.form.deposit_rate = 10
					this.$message.warning('请输入1-100之间')
					return
				}
			},

			// 底价计算
			toFloorPrice() {
				let fag = /^(?:[1-9]?\d|100)$/;
				// console.log(fag.test(this.form.rate));
				if (fag.test(this.form.rate)) {
					let floorPrice = this.form.cost * (this.form.rate / 100) + Number(this.form.cost);
					this.floorPrice = floorPrice.toFixed(2);
					// if(this.market_id != 2){ //联坤卖场
					//   if((this.form.rate*1)<8 || (this.form.rate*1)>15){
					//     this.form.rate = 8;
					//     this.$message.warning('比率范围在8-15%')
					//   }
					// }else{ //柳州卖场
					if ((this.form.rate * 1) < 0 || (this.form.rate * 1) > 99) {
						this.form.rate = 0;
						this.$message.warning('比率范围在0-99%')
					}
					// }

					// console.log(this.floorPrice,'11');
					// console.log(this.form.price,'22');
					// console.log(Number(this.floorPrice)>Number(this.form.price),'333');
					// 如果设置的底价大于售价，让底价等于售价
					// if (Number(this.floorPrice) > Number(this.form.price)) {
					//   this.floorPrice = this.form.price;
					//   this.form.rate = (
					//     (this.form.price - this.form.cost) /
					//     this.form.cost *
					//     100
					//   ).toFixed();
					//   // console.log(this.form.rate);
					//   this.$message({
					//     type: "info",
					//     message: "底价不可大于售价"
					//   });
					// }
				} else {
					this.form.rate = 0;
					this.$message({
						type: "warning",
						message: "请输入0-100的整数"
					});
					return;
				}
			},

      // 输入分佣比率
			inputRate() {
				let fag = /^(?:[1-9]?\d|100)$/;
				if (this.form.promotor_rate > 15 || this.form.promotor_rate < 0) {
					this.$message({
						type: "warning",
						message: "比率范围在0-15"
					});
					return;
				}
			},


			// 计算每个规格底价
			calcula(item) {
				let index = this.tableContent[0].length - 1; //供货价下标
				let index1 = this.tableContent[0].length - 2; //售价下标
				let costPrice = item[index].value; //供货价
				let nowPrice = item[index1].value; //售价
				// 底价
				let all = costPrice * (this.form.rate / 100) + Number(costPrice);
				// 判断底价是否大于售价
				if (all > nowPrice) {
					all = nowPrice;
				}
				return all;
			},

			//富文本上传图片
			handleImageAdded(file, Editor, cursorLocation, resetUploader) {
				// let file = event.target.files[0];
				let isLtSize = file.size / 1024 / 1024 < 10;
				// console.log(isLtSize);
				if (!isLtSize) {
					this.$message.warning("上传文件不能超过 10MB!");
					return;
				}
				this.editorLoading = true
				let form = new FormData();
				form.append("file", file);
				this.$http
					.post("/api/client/base/uploadfile", form)
					.then(result => {
						// console.log(result);
						// 你上传路径返回的url
						let url = result.data.url;
						// console.log(url);
						Editor.insertEmbed(cursorLocation, "image", url);
						resetUploader();
						this.editorLoading = false
					})
					.catch(err => {
						// console.log(err);
						this.editorLoading = false
					});
			},

			// 调分类数据
			init() {
				this.$http.get("/api/root/Cate/cateLst", {
					sale_type: this.form.sale_type,
					market_id: this.market_id
				}).then(res => {
					if (res.code == 1) {
						let cate_list = res.data.filter(item => item.child);
						this.cateList = cate_list;
					}
				});
				// 运费模板
				this.$http
					.post("/api/root/freight/lst", {
						store_id: this.store_id
					})
					.then(res => {
						console.log(res);
						if (res.code == 1) {
							this.freightAll = res.data;
						}
					});
				console.log(this.store_id);
			},

			// 返回
			handerBase() {
				// this.$router.go(-1);
				let page = this.$route.query.page
				let storeName = this.$route.query.storeName
				let shopName = this.$route.query.shopName
				this.$router.push({
					name: "shopList",
					query: {
						page,
						storeName,
						shopName
					}
				});
			},
			// 检测商品名字是否有输入
			handerName() {
				if (this.form.name == "") {
					this.nameColor = true;
					this.nameNull = true;
				} else {
					this.nameColor = false;
					this.nameNull = false;
				}
			},
			handerUnit() {
				if (this.form.unit == "") {
					this.nameColor = true;
					this.unitNull = true;
				} else {
					this.nameColor = false;
					this.unitNull = false;
				}
			},
			// 切换导航栏
			handerTabs(i) {
				this.tabsIndex = i;
				if (i == 0) {
					// this.changekpx()
					this.information = true;
					this.specifications = false;
					this.details = false;
				} else if (i == 1) {
					if (this.form.purchase_limit == 1) {
						if (this.form.limit_amount <= 0 || this.form.limit_amount == undefined) {
							this.$message.error("请填写限制金额");
							return;
						}
					}
					this.information = false;
					this.specifications = true;
					this.details = false;
				} else if (i == 2) {
					this.information = false;
					this.specifications = false;
					this.details = true;
				}
			},
			// 获取用户选中的商品分类
			handerClassif(e) {
				console.log(e);
				this.form.classification = e[e.length - 1];
			},

			// 上传商品图片
			handerFile(evnet) {
				if (this.imagesUrl.length >= 6) {
					this.$message.warning('最多上传6张图片！')
					return
				}
				let file = evnet.target.files[0];
				// this.$http.yaSuoImg(file)
				let isLtSize = file.size / 1024 / 1024 < 10;
				// console.log(isLtSize);
				if (!isLtSize) {
					this.$message.warning("上传文件不能超过 10MB!");
					return;
				}
				this.loading = true;
				let form = new FormData();
				form.append("file", file);
				this.$http
					.post("/api/client/base/uploadfile", form)
					.then(res => {
						// console.log(res);
						if (res.code == 1) {
							this.$message({
								showClose: true,
								message: "上传成功",
								type: "success"
							});
							this.loading = false;
						}
						let src = res.data.id;
						console.log(res);
						this.form.img.push(src);
						let imgPath = {
							image_path: ""
						};
						imgPath.image_path = res.data.url;
						this.imagesUrl.push(imgPath);
						evnet.target.value = "";
					})
					.catch(err => {
						this.$message({
							showClose: true,
							message: "上传失败",
							type: "error"
						});
						this.loading = false;
					});
			},

			// 删除商品图片
			deleteImg(index) {
				// console.log(index);
				// console.log(this.form.img);
				this.imagesUrl.splice(index, 1);
				this.form.img.splice(index, 1);
				console.log(this.imagesUrl);
				console.log(this.form.img);
			},

			// 上传规格图片
			async handerFiles(event, index, index1) {
				let file = event.target.files[0];
				let isLtSize = file.size / 1024 / 1024 < 10;
				// console.log(isLtSize);
				if (!isLtSize) {
					this.$message.warning("上传文件不能超过 10MB!");
					return;
				}
				let form = new FormData();
				// console.log(event);
				// console.log(index);
				form.append("file", file);
				this.$http.post("/api/client/base/uploadfile", form).then(res => {
					if (res.code == 1) {
						this.$message({
							showClose: true,
							message: "上传成功",
							type: "success"
						});
					}
					let src = res.data.id;
					// this.form.specifAll[i].child[index].specimg = src;
					let data = res.data;
					// console.log(data);
					// this.list[index].img = data.url;
					// this.list[index].img_id = data.id;
					this.tableContent[index][index1].path = data.url;
					this.tableContent[index][index1].img_id = data.id;
					// console.log(this.list);
				});
			},
			// 是否显示库存
			handerIpt() {
				this.hiddIpt = !this.hiddIpt;
				if (this.hiddIpt) {
					this.form.according = 1;
				} else {
					this.form.according = 2;
				}
			},
			handerYesNo() {
				this.hiddYesNo = !this.hiddYesNo;
				this.form.codings = "";
				this.form.codingss = "";
				this.form.codingsss = "";
				this.form.inventory = "";
				if (!this.hiddYesNo) {
					this.form.specsType = 2;
				} else {
					this.form.specsType = 1;
				}
			},

			// 打开添加规格
			// addSpecifs() {
			//   this.hiddYesNo = false;
			//   this.hiddtitle = true;
			// //新增规格
			// //
			// },

			// 删除规格
			downSpecif(index) {
				const title = this.list[index].title;
				const tempList = JSON.parse(JSON.stringify(this.list)); //删之前先保存一份用于后面判断
				this.list.splice(index, 1);
				//删除完让sort重新获取值  不然后面添加规格排序会乱
				this.list.forEach((item, index) => {
					item.sort = index;
				});
				if (!this.tableContent.length) {
					return false;
				}
				// 如果当前删除的规格里面没有值就不用在this.tableContent中删除数据
				if (!tempList[index].list.length) return false;
				// 如果删除的是最后一个规格，则清空所有数据
				if (this.tableContent[0][1].type != "规格") {
					this.tableContent = [];
					this.tableTitle = [];
					return false;
				}
				// 删除表中整列的数据
				this.deleteRowData(title);
				// 递归去重
				for (let i = 0; i < this.tableContent.length; i++) {
					for (let j = i + 1; j < this.tableContent.length; j++) {
						this.recursionJudgeValue(i, j, 0, true);
						if (this.delectFlag) {
							this.tableContent.splice(j, 1);
							j--;
						}
					}
				}
				// 重新生成表头
				this.handleTableHead();
			},
			// 递归去重
			recursionJudgeValue(i, j, count, flag) {
				let tempFlag =
					this.tableContent[i][count].value == this.tableContent[j][count].value;
				let tempCount = count;
				const flag2 = flag && tempFlag;
				if (tempCount < this.list.length) {
					tempCount++;
					this.recursionJudgeValue(i, j, tempCount, flag2);
				} else {
					this.delectFlag = flag2;
				}
			},
			// 删除表中一列的数据
			deleteRowData(title) {
				for (let i = 0; i < this.tableContent.length; i++) {
					value: for (let j = 0; j < this.tableContent[i].length; j++) {
						if (this.tableContent[i][j].key == title) {
							this.tableContent[i].splice(j, 1);
							break value;
						}
					}
				}
			},

			// // 删除当前规格
			downSpecif_child(index, index1) {
				this.hiddtitle = true;
				if (!this.tableContent.length) {
					this.list[index].list.splice(index1, 1);
					return false;
				}
				const length = this.list[index].list.length;
				const value = this.list[index].list[index1].value;
				const title = this.list[index].title;
				this.list[index].list.splice(index1, 1);
				if (length > 1) {
					// 如果有多个值时就删除this.tableContent中所有带有这个值的那一行
					content: for (let i = 0; i < this.tableContent.length; i++) {
						value: for (let j = 0; j < this.tableContent[i].length; j++) {
							if (this.tableContent[i][j].value == value) {
								this.tableContent.splice(i, 1);
								i--;
								break value;
							}
						}
					}
				}
				else {
					// 如果只有一个值 那么就把值从所有数据中删除 就是删除列
					this.list[index].new = true; //删除掉这个值 那么这个规格没有值了  就等同于是新添加的
					this.deleteRowData(title);
					if (
						this.tableContent.length === 1 &&
						this.tableContent[0][0].type != "规格"
					) {
						// 如果删除的是最后的规格和最后一个值就清空所有数据
						this.tableContent = [];
						this.tableTitle = [];
						return false;
					}
					// 重新生成表头
					this.handleTableHead();
				}
			},

			//添加规格项
			addSpecif() {
				if (!this.title) {
					// return this.$message.warning("请填写规格再添加");
					this.hiddspecifs = true;
					return;
				}
				let allTitle = this.list.map(item => {
					return item.title;
				});
				if (allTitle.indexOf(this.title) != -1) {
					return this.$message.warning("已添加过该规格");
				}
				// console.log(allTitle);
				this.title;
				this.hiddspecifs = false;
				this.list.push({
					img: "",
					title: this.title, //规格
					list: [], //规格值
					sort: this.list.length,
					new: this.tableContent.length ? true : false //用于判断是否新规格
				});
				// console.log(this.list);
				this.title = "";
			},

			//添加规格属性值
			addSku_child(index) {
				if (!this.list[index].value) {
					return this.$message.warning("请填写规格值再添加");
				} else {
					let allSku = this.list[index].list.map(item => {
						return item.value;
					});
					if (allSku.indexOf(this.list[index].value) != -1) {
						return this.$message.warning("已添加过该规格值");
					} else {
						this.list[index].list.push({
							img: this.list[index].img,
							img_id: this.list[index].img_id,
							value: this.list[index].value, //规格值
							new: this.tableContent.length ? true : false //用于判断是否新规格值
						});
						// console.log(this.list[index].list);
						// console.log(this.list[index]);
						this.list[index].value = "";
						this.list[index].img = "";
					}
					// console.log(this.list);
					// console.log(this.tableContent);
				}
			},

			// 刷新规格列表
			refreshSku() {
				console.log(this.list);
				if (!this.list.length) {
					this.$message.warning('请添加规格')
					return
				} else {
					for (let i = 0; i < this.list.length; i++) {
						if (!this.list[i].list.length) {
							this.$message.warning('请完善规格值')
							return
						}
					}
				}
				this.hiddtitle = false;
				this.hiddsku = true;
				//讲添加的规格项进行排序
				// function specsortFunction(propertyName) {
				//   return function(object1, object2) {
				//     let value1 = object1[propertyName].length;
				//     let value2 = object2[propertyName].length;
				//     if (value1 < value2) {
				//       return -1;
				//     } else if (value1 > value2) {
				//       return 1;
				//     } else {
				//       return 0;
				//     }
				//   };
				// }
				// // this.list.sort(specsortFunction("list"));
				// console.log(this.this);
				// console.log(this.form.spec_typelist);
				// console.log(this.list);
				// if (!this.list.length) return false;
				// let flag = false;
				// flag = this.list.some(item => {
				//   return item.list.length;
				// });
				// if (!flag) return false;
				this.handleTableHead();
				this.handleTableData();
				// console.log(this.tableContent);
			},

			// 生成表头
			handleTableHead() {
				this.tableTitle = [];
				this.list.forEach(item => {
					if (item.list.length) {
						this.tableTitle.push(item.title);
					}
				});
				this.tableTitle.push("规格图", "库存", "原价", "售价", "供货价");
			},

			// 处理表格中的数据
			handleTableData() {
				const listData = this.list.filter(item => item.list.length); //去掉没有值的规格
				// console.log(listData);
				if (this.tableContent.length) {
					// 表格中数据不是第一次添加时
					let tempList = []; //用于存放新加的规格和值
					let tempContentList = this.tableContent.length; //记录上一次数据的总长度
					listData.forEach((item, index) => {
						// console.log(item);
						item.list.forEach((item2, index2) => {
							// console.log(item2);
							if (item2.new) {
								// console.log('111111');
								// console.log(item2);
								//新添加的值
								let flag = false; // flag用于判断新值有没有添加进tempList
								let count = -1;
								// console.log(listData);
								flag = tempList.some((sitem, sindex) => {
									count++;
									return sitem.title == item.title;
								});
								// console.log(flag);
								if (flag) {
									//如果添加过则直接在里面的list追加
									tempList[count].list.push(item2);
								} else {
									//没添加过就添加一个新的对象
									tempList.push({
										title: item.title,
										list: [item2],
										new: item.new,
										sort: item.sort
									});
									// console.log(tempList);
								}
							}
						});
					});
					// console.log(tempList);
					tempList.forEach(item => {
						// console.log(item);
						const list = [];
						// list代表所有新值的规格和其他规格匹配的数据
						if (item.new && item.list.length == 1) {
							// 如果新加的规格的值只有一个，那么直接在每一列加新值
							for (let i = 0; i < tempContentList; i++) {
								this.tableContent[i].splice(item.sort, 0, {
									type: "规格",
									value: item.list[0].value,
									sort: item.sort,
									key: item.title
								});
							}
						} else {
							// 如果新加的规格的值大于一个，那么先在每一列插入新值
							// 然后再拿其他值互相匹配
							if (item.new && item.list.length > 1) {
								for (let i = 0; i < tempContentList; i++) {
									this.tableContent[i].splice(item.sort, 0, {
										type: "规格",
										value: item.list[0].value,
										sort: item.sort,
										key: item.title
									});
								}
								// 第一个值已经加进去，所以要删掉
								item.list.splice(0, 1);
							}
							// 先把新加的值加进去
							// console.log(item);
							// console.log(list);
							list.push(item);
							// console.log(list);
							listData.forEach(listItem => {
								listItem.list.forEach(listItem2 => {
									item.list.forEach(item2 => {
										if (listItem2.value == item2.value) {
											// 上面的新值已经加进去所以要在原来的listData中做标记
											// 避免下面出现重复的组合
											listItem2.disabled = true;
										}
									});
								});
							});
							listData.forEach(listItem => {
								if (listItem.title !== item.title) {
									// 深拷贝避免影响原来的数据
									let tempListItem = JSON.parse(JSON.stringify(listItem));
									for (let count = 0; count < tempListItem.list.length; count++) {
										if (tempListItem.list[count].disabled) {
											//已经加过的值删掉
											tempListItem.list.splice(count, 1);
											count--;
										}
									}
									list.push(tempListItem); // 加进list组合成新的数据
								}
							});
							list.sort((n1, n2) => n1.sort - n2.sort); //排序 避免新加的表中数据和表头对应不上
							// console.log(list);
							this.transformData(list);
						}
					});
					// 生成后把所有的值初始化 用于下次生成判断新值
					this.list.forEach(item => {
						item.new = false;
						item.list.forEach(item2 => {
							item2.new = false;
							item2.disabled = false;
						});
					});
					return false;
				}
				// console.log(listData);
				this.transformData(listData);
			},

			transformData(list) {
				const arr = [];
				// console.log(list);
				// 这里改造一下数据
				list.forEach(item => {
					// console.log(item);
					const tempList = [];
					item.list.forEach(item2 => {
						// console.log(item2);
						let obj = {
							type: "规格",
							value: item2.value,
							sort: item.sort,
							key: item.title
						};
						tempList.push(obj);
					});
					arr.push(tempList);

					// console.log(arr);
				});
				// 再改造成真正的表中数据类型
				const data = this.cartesianProductOf(...arr);
				// 这里给表中每行加一些写死的值
				data.forEach(item => {
					item.push({
						type: "规格图",
						path: '',
						img_id: '',
						rowspan: 1
					});
					item.push({
						type: "库存",
						value: "",
						rowspan: 1
					});
					item.push({
						type: "原价",
						value: "",
						rowspan: 1
					});
					item.push({
						type: "售价",
						value: "",
						rowspan: 1
					});
					item.push({
						type: "供货价",
						value: "",
						rowspan: 1
					});
				});
				//与原来的数据合并
				this.tableContent.push(...data);
				// console.log(this.tableContent, "tableContent");
			},
			// 笛卡尔积
			cartesianProductOf() {
				return Array.prototype.reduce.call(
					arguments,
					function(a, b) {
						var ret = [];
						a.forEach(function(a) {
							b.forEach(function(b) {
								ret.push(a.concat(b));
								// ret.push([...a, ...b]);
							});
						});
						return ret;
					},
					[
						[]
					]
				);
			},

			// 下一步/上一步
			save(i) {
				// console.log(this.form.sku);
				// console.log(this.form.specifAll);
				// console.log(this.form.spec_sku);
				this.handerTabs(i);
			},

			// 保存
			saveFile() {
				let url = this.form.id ?
					"/api/root/ProductShop/edit" :
					"/api/root/ProductShop/add";
				let store_id = this.$route.query.store_id;
				let product_id = this.form.id;
				let product_title = this.form.name;
				let unit = this.form.unit;
				let keyword = this.form.keywords;
				let cate_id = this.form.classification;
				let product_type = this.form.shoptype;
				let s_type = [];
				this.form.shoptypes.forEach(v => {
					s_type.push(v);
				});

				s_type = s_type.join(",");
				let price =
					this.form.price >= 0 ?
					this.form.price :
					this.$message.error("售价不能小于0");
				let cost_price =
					this.form.cost >= 0 ?
					this.form.cost :
					this.$message.error("供货价不能小于0");
				let primary_price =
					this.form.priced >= 0 ?
					this.form.priced :
					this.$message.error("原价不能小于0");
				let pay_way = [];
				this.form.payment.forEach(v => {
					pay_way.push(v);
				});
				pay_way = pay_way.join(",");
				let move_type = this.form.freight;
				let move_id = this.form.template;
				let move_price = this.form.freightPrice;
				let status = this.form.shelves;
				let set_sale_time = this.form.shelvesTime;
				// console.log(this.form.shelves_time);
				let start_sale_time = this.form.shelves_time[0];
				// ? (new Date(this.form.shelves_time[0]).getTime())/1000
				// : "";
				let end_sale_time = this.form.shelves_time[1];
				// ?  (new Date(this.form.shelves_time[1]).getTime())/1000
				// : "";

				// console.log(start_sale_time,end_sale_time,new Date(this.form.shelves_time[0]).getTime(),new Date(this.form.shelves_time[1]).getTime());
				let code = this.form.codings ? this.form.codings : "";
				// if(this.form.codings == '') {
				// 	code = this.form.spec_sku[0].spec_code;
				// }else {
				// 	code = this.form.codings;
				// }
				let barcode = this.form.codingss ? this.form.codingss : "";
				// if(this.form.codingss == '') {
				// 	barcode = this.form.spec_sku[0].spec_barcode;
				// }else {
				// 	barcode = this.form.codingss;
				// }
				let weight = this.form.codingsss ? this.form.codingsss : "";
				// if(this.form.codingsss == '') {
				// 	weight = this.form.spec_sku[0].spec_weight;
				// }else {
				// 	weight = this.form.codingsss;
				// }
				let is_show_stock = this.form.according;
				let stock_type = this.form.reduInventory;
				let specs_type = this.form.specsType;
				let round_imgs = [];

				// this.form.img.forEach(v => {
				//   round_imgs.push(v);
				//   // console.log(v);
				// });
				this.fileList.map(v => {
					if (v.response) {
						round_imgs.push(v.response.data.id);
					} else {
						round_imgs.push(v.id);
					}

					// console.log(v);
				});
				// console.log(this.form.img);
				// console.log(this.imagesUrl);
				round_imgs = round_imgs.join(",");
				console.log(round_imgs, '轮播图1');
				console.log(this.fileList, '轮播图');
				let subtitle = this.form.subtitle;
				let short_title = this.form.shorttitle;
				// let details = this.$refs.myeditor.editor.root.innerHTML; // 商品详情
				let details = this.form.details; // 商品详情
				let num =
					this.form.inventory >= 0 ?
					this.form.inventory :
					this.$message.error("库存不能小于0"); // 库存
				let parameter = [];
				let sku_c = [];
				let obj = {};
				let child = [];

				this.list.forEach(item => {
					obj = {
						specifs: item.title,
						child: child
					};
					parameter.push(obj);
				});
				for (let i = 0; i < this.list.length; i++) {
					for (let key in this.list[i]) {
						if (key == "list") {
							// console.log(this.list[i][key]);
							sku_c.push(this.list[i][key]);
						}
					}
				}
				let k = [];
				for (let x = 0; x < sku_c.length; x++) {}

				//改变每一组的key名字，然后赋值给parameter
				for (let i = 0; i < parameter.length; i++) {
					let arr = [];
					let arr1 = [];
					arr.push(arr1);
					// console.log(arr);
					arr[i] = sku_c[i].map(item => ({
						specif: item.value,
						specimg: item.img_id ? item.img_id : ""
					}));
					parameter[i].child = arr[i];
				}
				// console.log(sku_c); //============
				// console.log(parameter);

				//将对应的每一项信息push到sku_lst中
				let sku_lst = [];
				let sku_obj1 = {};
				console.log(this.tableContent, '=====');
				this.tableContent.map((item1, index1) => {
					console.log(item1, 'itemitemitme');
					sku_obj1 = {
						sku_id: item1[0].sku_id ? item1[0].sku_id : 0,
						img: item1[item1.length - 5].img_id,
						num: item1[item1.length - 4].value >= 0 ?
							item1[item1.length - 4].value :
							this.$message.error("规格库存不能小于0"),
						primary_price: item1[item1.length - 3].value >= 0 ?
							item1[item1.length - 3].value :
							this.$message.error("规格原价不能小于0"),
						price: item1[item1.length - 2].value >= 0 ?
							item1[item1.length - 2].value :
							this.$message.error("规格售价不能小于0"),
						cost_price: item1[item1.length - 1].value >= 0 ?
							item1[item1.length - 1].value :
							this.$message.error("规格供货价不能小于0"),
						attribute: []
					};

					//将每一行的规格push到对应的attribute中
					for (let k = 0; k < item1.length - 5; k++) {
						// console.log(item1[k]);
						let obj4 = {
							key: item1[k].key,
							value: item1[k].value
						};
						// console.log(obj4);
						// let obj5 = {};
						// obj5[item1[k].key] = item1[k].value;
						sku_obj1.attribute.push(obj4);
					}
					sku_lst.push(sku_obj1);
				});
				//===========================================================
				// console.log(sku_obj1);
				// console.log(sku_lst);

				// console.log(this.form.spec_sku);
				console.log(sku_lst, 'skuskusksu');
				sku_lst.map(item => {
					if (
						item.num < 0 ||
						item.primary_price < 0 ||
						item.price < 0 ||
						item.cost_price < 0
					) {
						return false;
					}
				});
				// if(){
				//   return false
				// }

				parameter = JSON.stringify(parameter);
				sku_lst = JSON.stringify(sku_lst);
				// console.log(sku_lst);
				// console.log(parameter);
				// console.log(sku_lst);
				// console.log(this.form.img);

				// 比率--
				let fag = /^(?:[1-9]?\d|100)$/;
				let rate = null;
				if (fag.test(this.form.rate)) {
					rate = this.form.rate / 100;
				} else {
					this.$message({
						type: "warning",
						message: "请输入0-100的整数比率"
					});
					return;
				}
        if (this.form.promotor_rate > 15 || this.form.promotor_rate < 0) {
					this.$message({
						type: "warning",
						message: "分佣比率范围在0-15"
					});
					return;
				}

				this.$http
					.post(url, {
						product_id,
						store_id: store_id,
						product_title: product_title,
						unit: unit,
						keyword: keyword,
						cate_id: cate_id,
						product_type: product_type,
						s_type: s_type,
						price: price,
						cost_price: cost_price,
						primary_price: primary_price,
						pay_way: pay_way,
						move_type: move_type,
						move_id: move_id,
						move_price: move_price,
						status: status,
						set_sale_time: set_sale_time,
						start_sale_time: start_sale_time,
						end_sale_time: end_sale_time,
						code: code,
						barcode: barcode,
						weight: weight,
						is_show_stock: is_show_stock,
						stock_type: stock_type,
						specs_type: specs_type,
						round_imgs: round_imgs,
						subtitle: subtitle,
						short_title: short_title,
						details: details,
						num: num,
						parameter: parameter,
						sku_lst: sku_lst,
						rate: rate,
						cool_show: this.form.kpx,
						set_deposit_status: this.form.set_deposit_status,
						set_material: this.form.setMaterial, //选材中心
						deposit_rate: this.form.deposit_rate / 100,
						sale_type: this.form.sale_type,
						limit_amount: this.form.limit_amount,
						purchase_limit: this.form.purchase_limit,
						promotor_rate: this.form.promotor_rate,
					})
					.then(res => {
						if (res.code == 1) {
							if (this.form.id) {
								this.$message({
									showClose: true,
									message: "修改成功",
									type: "success"
								});
								let page = this.$route.query.page
								let storeName = this.$route.query.storeName
								let shopName = this.$route.query.shopName
								this.$router.push({
									name: "shopList",
									query: {
										page,
										storeName,
										shopName
									}
								});
							} else {
								this.$message({
									showClose: true,
									message: "添加成功",
									type: "success"
								});
								this.$router.push({
									path: '/shopList'
								})
							}
							console.log(res);
						} else {
							this.$message.error(res.msg);
						}
					});
			},

			//酷品秀
			changekpx() {
				console.log(this.form.kpx)
				if (this.form.kpx) {
					document.getElementById('kpx').innerHTML = '';

					const {
						ViewerSDK
					} = koolViewer;
					const viewer = new ViewerSDK({
						mount: document.getElementById('kpx'),
						modelId: this.form.kpx,
					});
					document.getElementById('kpx-box').style.display = 'block';
					viewer.start().then(() => {}).catch(err => {});
				} else {
					document.getElementById('kpx-box').style.display = 'none';
				}
			}
		},
		components: {
			VueEditor
		}
	};
</script>

<style lang="less">
	@import "shopDetail.less";
</style>
